<?php

declare(strict_types=1);

namespace app\common\model\User;

use app\common\model\Config;
use app\common\model\Region;
use think\model\concern\SoftDelete;
use think\Model;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    // 使用软删除
    use SoftDelete;

    // 指定数据表
    protected $table = 'pre_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 定义创建时间
    protected $createTime = 'createtime';

    // 定义更新时间
    protected $updateTime = false;

    // 软删除字段
    protected $deleteTime = 'deletetime';

    // 定义追加字段列表 => 前后端分离项目
    protected $append = [
        // 地区字段
        'region_text',
        'sex_text',
        'avatar_cdn',
        'cover_cdn',
        'region',
        'wxAvatar_cdn'
    ];

    // 定义不存在字段 region_text => RegionText
    public function getRegionTextAttr($value, $data)
    {
        $province = Region::where(['code' => $data['province']])->value('name');
        $city = Region::where(['code' => $data['city']])->value('name');
        $district = Region::where(['code' => $data['district']])->value('name');

        $region_text = '';
        if ($province) {
            $region_text .= $province . '-';
        }
        if ($city) {
            $region_text .= $city . '-';
        }
        if ($district) {
            $region_text .= $district;
        }
        return $region_text;
    }

    public function getSexTextAttr($value, $data)
    {
        $sex = [0 => '保密', 1 => '男', 2 => '女'];

        return $sex[$data['sex']];
    }

    public function getAvatarCdnAttr($value, $data)
    {
        $avatar = is_file('./' . $data['avatar']) ? $data['avatar'] : '/static/home/res/images/avatar/default.png';

        $cdn = Config::where(['key' => 'cdn'])->value('value');

        return $cdn . $avatar;
    }
    public function getCoverCdnAttr($value, $data)
    {
        $cover = is_file('./' . $data['cover']) ? $data['cover'] : '/static/home/res/images/cover.jpg';

        $cdn = Config::where(['key' => 'cdn'])->value('value');

        return $cdn . $cover;
    }
    public function getRegionAttr($value, $data)
    {
        $province = Region::where(['code' => $data['province']])->find();
        $city = Region::where(['code' => $data['city']])->find();
        $district = Region::where(['code' => $data['district']])->find();
        if($province||$city||$district){
            $data = [
                $province['name'],
                $city['name'],
                $district['name'],
            ];
            return $data;
        }
    }
    public function getWxAvatarCdnAttr($value, $data)
    {
        $wxAvatar = is_file('./' . $data['wxAvatar']) ? $data['wxAvatar'] : '/static/home/res/images/avatar/0.png';

        $cdn = Config::where(['key' => 'cdn'])->value('value');

        return $cdn . $wxAvatar;
    }
}
